package com.google.appengine.examples;

import com.google.appengine.api.files.FileReadChannel;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * An implementation of {@link FileReadChannel} that builds a read channel for local files.
 */
public class LocalFileReadChannel implements FileReadChannel {

  private final FileChannel fileChannel;

  @SuppressWarnings("resource") // FileChannel closes RandomAccessFile
  public LocalFileReadChannel(String qualifiedFileName) throws FileNotFoundException {
    fileChannel = new RandomAccessFile(qualifiedFileName, "r").getChannel();
  }

  @Override
  public int read(ByteBuffer dst) throws IOException {
    return fileChannel.read(dst);
  }

  @Override
  public boolean isOpen() {
    return fileChannel.isOpen();
  }

  @Override
  public void close() throws IOException {
    fileChannel.close();
  }

  @Override
  public long position() throws IOException {
    return fileChannel.position();
  }

  @Override
  public FileReadChannel position(long newPosition) throws IOException {
    fileChannel.position(newPosition);
    return this;
  }
}
